package cn.zoujiedev.netty.core.serialization;

import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.SerializerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import java.io.ByteArrayOutputStream;

/**
 * @Classname HessianDecoder
 * @Description
 * @Date 2022-11-3 13:44
 * @Created by zoujie
 */
public class HessianEncoder implements ObjectEncoder{

  private static final byte[] LENGTH_PLACEHOLDER = new byte[4];

  @Override
  public void encode(Object msg, ByteBuf out) throws Exception{

    ByteBufOutputStream output = null;
    Hessian2Output hessian2Output = null;
    try {
      int lengthPos = out.writerIndex();
      out.writeBytes(LENGTH_PLACEHOLDER);

      output = new ByteBufOutputStream(out);
      hessian2Output = new Hessian2Output(output);
      hessian2Output.setSerializerFactory(new SerializerFactory());

      hessian2Output.writeObject(msg);
      hessian2Output.flush();

      out.setInt(lengthPos,out.writerIndex() - lengthPos - LENGTH_PLACEHOLDER.length);

    }finally {
      if(output != null){
        output.close();
      }
      if(hessian2Output != null){
        hessian2Output.close();
      }
    }
  }
}
